package cn.view;

import cn.dao.PayDetailDao;
import cn.dao.PayMainDao;
import cn.entity.PayDetail;
import cn.entity.PayMain;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class PaySQView extends JInternalFrame {

    private JTable payMainTable;
    private JTable payDetailTable;
    private JTextArea statsArea;
    private PayMainDao payMainDao;
    private PayDetailDao payDetailDao;

    public PaySQView() {
        super("采购信息统计", true, true, true, true);
        setTitle("采购统计信息查询");
        setSize(800, 500);
        setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE); // 设置关闭操作为隐藏窗口
        setLayout(new BorderLayout());

        payMainDao = new PayMainDao();
        payDetailDao = new PayDetailDao();

        payMainTable = new JTable();
        JScrollPane payMainScrollPane = new JScrollPane(payMainTable);

        payDetailTable = new JTable();
        JScrollPane payDetailScrollPane = new JScrollPane(payDetailTable);

        statsArea = new JTextArea();
        statsArea.setEditable(false);
        JScrollPane statsScrollPane = new JScrollPane(statsArea);

        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, payMainScrollPane, payDetailScrollPane);
        splitPane.setResizeWeight(0.5);

        add(splitPane, BorderLayout.CENTER);
        add(statsScrollPane, BorderLayout.SOUTH);

        loadPayMainData();
        loadAllPayDetailData(); // 初始加载所有采购明细
        payMainTable.getSelectionModel().addListSelectionListener(e -> loadPayDetailData());
        loadStatistics();

        setVisible(true);
    }

    private void loadPayMainData() {
        List<Object[]> payMainData = payMainDao.selectAll();
        String[] columnNames = {"采购清单号", "员工编号", "采购总数量", "采购总价", "采购时间", "备注"};
        DefaultTableModel model = new NonEditableTableModel(columnNames, 0);
        for (Object[] row : payMainData) {
            model.addRow(row);
        }
        payMainTable.setModel(model);
    }

    private void loadPayDetailData() {
        int selectedRow = payMainTable.getSelectedRow();
        if (selectedRow != -1) {
            Object midObj = payMainTable.getValueAt(selectedRow, 0);
            if (midObj instanceof Integer) {  // 确认midObj是Integer类型
                int mid = (Integer) midObj;
                List<Object[]> payDetailData = payDetailDao.selectAll();
                String[] columnNames = {"采购明细号", "采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
                DefaultTableModel model = new NonEditableTableModel(columnNames, 0);
                for (Object[] row : payDetailData) {
                    if ((int) row[1] == mid) {
                        model.addRow(row);
                    }
                }
                payDetailTable.setModel(model);
            } else if (midObj instanceof String) {  // 兼容String类型以防万一
                try {
                    int mid = Integer.parseInt((String) midObj);
                    List<Object[]> payDetailData = payDetailDao.selectAll();
                    String[] columnNames = {"采购明细号", "采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
                    DefaultTableModel model = new NonEditableTableModel(columnNames, 0);
                    for (Object[] row : payDetailData) {
                        if ((int) row[1] == mid) {
                            model.addRow(row);
                        }
                    }
                    payDetailTable.setModel(model);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "采购主表号码必须是整数。", "错误", JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                }
            } else {
                System.err.println("未预期的数据类型：" + midObj.getClass().getName());
            }
        } else {
            loadAllPayDetailData(); // 如果没有选中行，加载所有采购明细
        }
    }

    private void loadAllPayDetailData() {
        List<Object[]> payDetailData = payDetailDao.selectAll();
        String[] columnNames = {"采购明细号", "采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
        DefaultTableModel model = new NonEditableTableModel(columnNames, 0);
        for (Object[] row : payDetailData) {
            model.addRow(row);
        }
        payDetailTable.setModel(model);
    }

    private void loadStatistics() {
        List<PayMain> payMains = payMainDao.queryPayMain(new PayMain());
        List<PayDetail> payDetails = payDetailDao.queryPayDetails(new PayDetail());

        int totalQuantity = payMains.stream().mapToInt(PayMain::getMcount).sum();
        double totalAmount = payMains.stream().mapToDouble(PayMain::getPaytotal).sum();

        StringBuilder stats = new StringBuilder();
        stats.append("总采购数量: ").append(totalQuantity).append("\n");
        stats.append("总采购金额: ").append(totalAmount).append("\n");

        statsArea.setText(stats.toString());
    }


}

class NonEditableTableModel extends DefaultTableModel {
    public NonEditableTableModel(Object[] columnNames, int rowCount) {
        super(columnNames, rowCount);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
}
